// server.js
let express = require('express')
let multer = require('multer')
let cors = require('cors')
let fs = require('fs')
let app = express()

// 定义上传的目录
let upload = multer({ dest: 'uploads/' })

// 允许跨域
app.use(cors())

// 实现文件上传
app.post('/upload', upload.single('avatar'), (req, res) => {
  console.log(req.body) //接收文本信息
  console.log(req.file) //接收文件信息
  // 判断是否有文件上传
  if (req.file) {
    // 进行文件的重命名即可 fs.rename
    let { originalname, destination, filename } = req.file
    let dotIndex = originalname.lastIndexOf('.')
    let ext = originalname.substring(dotIndex)
    let oldPath = `${destination}${filename}`
    let newPath = `${destination}${filename}${ext}`
    fs.rename(oldPath, newPath, (err) => {
      if (err) {
        throw err
      }
      res.json({ message: '上传文件成功', path: newPath })
    })
  } else {
    res.json({ message: '没有上传文件' })
  }
})

app.listen(3000, () => {
  console.log('server is running at port 3000')
})
